<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Object.keys,遍历," />





  <link rel="alternate" href="/atom.xml" title="I'm Minizh" type="application/atom+xml" />






<meta name="description" content="js 中几种遍历对象的方法，包括 for..of、for..in、Object.keys、Object.getOwnProperty,它们在使用场景方面各有不同。 js 对象的属性中可直接用、可访问到的属性分为数据属性和访问器属性。 数据属性（实际存储属性值的属性）的四大特性：{      value: 属性值,     writable: true/false,  //控制是否可修改     e">
<meta name="keywords" content="Object.keys,遍历">
<meta property="og:type" content="article">
<meta property="og:title" content="利用Object.keys遍历(forEach&#x2F;map)对象数组，合并">
<meta property="og:url" content="http://yoursite.com/2018/08/20/objectKeys/index.html">
<meta property="og:site_name" content="I&#39;m Minizh">
<meta property="og:description" content="js 中几种遍历对象的方法，包括 for..of、for..in、Object.keys、Object.getOwnProperty,它们在使用场景方面各有不同。 js 对象的属性中可直接用、可访问到的属性分为数据属性和访问器属性。 数据属性（实际存储属性值的属性）的四大特性：{      value: 属性值,     writable: true/false,  //控制是否可修改     e">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://i.imgur.com/gOOuYv0.png">
<meta property="og:updated_time" content="2018-08-19T09:48:36.605Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="利用Object.keys遍历(forEach&#x2F;map)对象数组，合并">
<meta name="twitter:description" content="js 中几种遍历对象的方法，包括 for..of、for..in、Object.keys、Object.getOwnProperty,它们在使用场景方面各有不同。 js 对象的属性中可直接用、可访问到的属性分为数据属性和访问器属性。 数据属性（实际存储属性值的属性）的四大特性：{      value: 属性值,     writable: true/false,  //控制是否可修改     e">
<meta name="twitter:image" content="https://i.imgur.com/gOOuYv0.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Minizh'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2018/08/20/objectKeys/"/>





  <title>利用Object.keys遍历(forEach/map)对象数组，合并 | I'm Minizh</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta custom-logo">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">I'm Minizh</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">ZH的个人博客</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
        
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
        
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
        
          
            <li class="menu-item menu-item-categories">
              <ul class="category-list"><li class="category-list-item"><a class="category-list-link" href="/categories/js/">js</a><span class="category-list-count">5</span><ul class="category-list-child"><li class="category-list-item"><a class="category-list-link" href="/categories/js/ES6/">ES6</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/js/Object-keys/">Object.keys</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/js/js遍历/">js遍历</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/js/异步/">异步</a><span class="category-list-count">2</span></li></ul></li><li class="category-list-item"><a class="category-list-link" href="/categories/工具类/">工具类</a><span class="category-list-count">3</span><ul class="category-list-child"><li class="category-list-item"><a class="category-list-link" href="/categories/工具类/MarkDown语法/">MarkDown语法</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/工具类/Smark/">Smark</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/工具类/hexo/">hexo</a><span class="category-list-count">1</span></li></ul></li></ul>
            </li>
          
        
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
        
      
        
        <li class="menu-item menu-item-sitemap">
          <a href="/atom.xml" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-sitemap"></i> <br />
            
            站点地图
          </a>
        </li>
        
      
        
        <li class="menu-item menu-item-commonweal">
          <a href="/2018/08/19/404/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-heartbeat"></i> <br />
            
            公益404
          </a>
        </li>
        
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2018/08/20/objectKeys/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="你就像谜一样">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/1383101481859.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="I'm Minizh">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">利用Object.keys遍历(forEach/map)对象数组，合并</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-08-20T20:30:15+08:00">
                2018-08-20
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/js/" itemprop="url" rel="index">
                    <span itemprop="name">js</span>
                  </a>
                </span>

                
                
                  ， 
                
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/js/Object-keys/" itemprop="url" rel="index">
                    <span itemprop="name">Object.keys</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>js 中几种遍历对象的方法，包括 for..of、for..in、Object.keys、Object.getOwnProperty,它们在使用场景方面各有不同。</p>
<p>js 对象的属性中可直接用、可访问到的属性分为数据属性和访问器属性。</p>
<h4 id="数据属性（实际存储属性值的属性）的四大特性："><a href="#数据属性（实际存储属性值的属性）的四大特性：" class="headerlink" title="数据属性（实际存储属性值的属性）的四大特性："></a>数据属性（实际存储属性值的属性）的四大特性：</h4><pre><code>{
     value: 属性值,
    writable: true/false,  //控制是否可修改
    enumerable: true/false, //控制是否可被for in遍历
    configurable: true/false, //1. 控制是否可删除 2. 控制是否可修改前两个特性  3.一旦改为false不可逆
}
</code></pre><h4 id="访问器属性（不实际存储数据，专门提供对其它数据-变量的保护）的四大特性："><a href="#访问器属性（不实际存储数据，专门提供对其它数据-变量的保护）的四大特性：" class="headerlink" title="访问器属性（不实际存储数据，专门提供对其它数据/变量的保护）的四大特性："></a>访问器属性（不实际存储数据，专门提供对其它数据/变量的保护）的四大特性：</h4><pre><code>{
    get:function(){return this.隐藏属性;},
    set:function(val){
    //如果val符合条件
        this.隐藏属性=val
    //否则
        报错
},
enumerable, configurable
}
</code></pre><h3 id="1-for-in"><a href="#1-for-in" class="headerlink" title="1. for..in"></a>1. for..in</h3><hr>
<p>返回的是所有能够通过对象访问的、可枚举的属性，既包括存在于实例中的属性，也包括存在于原型中的实例,不能保证属性按对象原来的顺序输出。（可枚举-自身-原型）</p>
<pre><code>var obj = {a:1, b:2, c:3};

for (var prop in obj) {
  console.log(&quot;obj.&quot; + prop + &quot; = &quot; + obj[prop]);
}
// Output:
// &quot;obj.a = 1&quot;
// &quot;obj.b = 2&quot;
// &quot;obj.c = 3&quot;
</code></pre><h3 id="2-Object-keys"><a href="#2-Object-keys" class="headerlink" title="2. Object.keys"></a>2. Object.keys</h3><hr>
<p>用于获取对象自身所有的可枚举的属性值，但不包括原型中的属性，然后返回一个由属性名组成的数组。注意它同 for..in 一样不能保证属性按对象原来的顺序输出。（可枚举-自身）</p>
<pre><code>// 数组
var arr = [&apos;a&apos;, &apos;b&apos;, &apos;c&apos;];
console.log(Object.keys(arr)); // console: [&apos;0&apos;, &apos;1&apos;, &apos;2&apos;]

// 类数组对象
var obj = { 0: &apos;a&apos;, 1: &apos;b&apos;, 2: &apos;c&apos; };
console.log(Object.keys(obj)); // console: [&apos;0&apos;, &apos;1&apos;, &apos;2&apos;]

// 类数组对象-随机下标
var anObj = { 100: &apos;a&apos;, 2: &apos;b&apos;, 7: &apos;c&apos; };
console.log(Object.keys(anObj)); // console: [&apos;2&apos;, &apos;7&apos;, &apos;100&apos;]

// 不可枚举属性getFoo
var myObj = Object.create({}, {
  getFoo: {
value: function () { return this.foo; }
  }
});
myObj.foo = 1;
console.log(Object.keys(myObj)); // console: [&apos;foo&apos;]
</code></pre><h3 id="3-Object-getOwnProperty"><a href="#3-Object-getOwnProperty" class="headerlink" title="3. Object.getOwnProperty"></a>3. Object.getOwnProperty</h3><hr>
<p>如果你想获取一个对象的所有属性，甚至包括不可枚举的，则可用该方法。其返回对象的所有自身属性的属性名组成的数组，但不会获取原型链上的属性。（可枚举&amp;不可枚举-自身）</p>
<pre><code>//获取不可枚举属性
var my_obj = Object.create({}, {
  getFoo: {
value: function() { return this.foo; },
enumerable: false
  }
});
my_obj.foo = 1;

console.log(Object.getOwnPropertyNames(my_obj).sort()); // [&quot;foo&quot;, &quot;getFoo&quot;]
</code></pre><p>下面的例子演示了该方法不会获取到原型链上的属性：</p>
<pre><code>function ParentClass() {}
ParentClass.prototype.inheritedMethod = function() {};

function ChildClass() {
  this.prop = 5;
  this.method = function() {};
}

ChildClass.prototype = new ParentClass;
ChildClass.prototype.prototypeMethod = function() {};

console.log(
  Object.getOwnPropertyNames(
new ChildClass()  // [&quot;prop&quot;, &quot;method&quot;]
  )
);
</code></pre><h3 id="4-for-of"><a href="#4-for-of" class="headerlink" title="4. for..of"></a>4. for..of</h3><hr>
<p>es6 新增方法，主要来遍历可迭代的对象（包括 Array, Map, Set, arguments 等），它主要用来获取对象 value 值，而 for..in 主要获取对象 key 值。<br>另外：可以由 break, continue, throw 或 return 终止。在这些情况下，迭代器关闭。</p>
<pre><code>let iterable = [10, 20, 30];
for (let value of iterable) {
value += 1;
console.log(value);
}
// 11
// 21
// 31
</code></pre><p>与 for..in 循环之间的区别：</p>
<pre><code>Object.prototype.objCustom = function() {};
Array.prototype.arrCustom = function() {};

let iterable = [3, 5, 7];
iterable.foo = &apos;hello&apos;;

for (let i in iterable) {
  console.log(i); //  0, 1, 2, &quot;foo&quot;, &quot;arrCustom&quot;, &quot;objCustom&quot;
}

for (let i in iterable) {
  if (iterable.hasOwnProperty(i)) {
console.log(i); //  0, 1, 2, &quot;foo&quot;
  }
}

for (let i of iterable) {
  console.log(i); //  3, 5, 7
}
</code></pre><h2 id="小结"><a href="#小结" class="headerlink" title="小结"></a>小结</h2><p>其实这几个方法之间的差异主要在属性是否可可枚举，是来自原型，还是实例。<br>图片描述</p>
<p>开发中的实际应用<br>需求：将如下两个从后台不同端口获取的 json 对象数组整合处理成如下注释部分的 json 对象</p>
<pre><code>var goodsSpecJSON = [{
&quot;SpecA&quot;: &quot;颜色&quot;
}, {
&quot;SpecB&quot;: &quot;容量&quot;
}, {
&quot;SpecC&quot;: &quot;大小&quot;
}, {
&quot;SpecD&quot;: &quot;尺寸&quot;
}, {
&quot;SpecE&quot;: &quot;套餐&quot;
}];
var goodsSpecList = [{
c_id: 3133,
costPrice: 0,
discountPrice: 0,
earn: 0,
etime: null,
flag: 0,
goodsDetailCount: 199,
goodsDetailId: &quot;100PgQ2xy08121409mY27&quot;,
goodsDetailInventory: 199,
goodsDetailOff: 0,
goodsDetailPic: &quot;/upload/messageImage/1523281057461_Personal.jpg,/upload/messageImage/1523282906972_Personal.jpg,/upload/messageImage/1523283570897_Personal.jpg&quot;,
goodsDetailPrice: 188,
goodsDetailSpec: &quot;&quot;,
goodsId: &quot;00Y1kR4r1029X822731o0&quot;,
isHost: 0,
managerEarn: 0,
postage: 10,
profit: 0,
specA: &quot;红色&quot;,
specB: &quot;32G&quot;,
specC: &quot;小&quot;,
specD: &quot;4.7寸&quot;,
specE: &quot;套餐一&quot;,
unionEarn: 0,
vipPrice: 0
}, {
c_id: 3134,
costPrice: 0,
discountPrice: 0,
earn: 0,
etime: null,
flag: 0,
goodsDetailCount: 199,
goodsDetailId: &quot;100PgQ2xy08121409mY27&quot;,
goodsDetailInventory: 199,
goodsDetailOff: 0,
goodsDetailPic: &quot;/upload/messageImage/1523281057461_Personal.jpg,/upload/messageImage/1523282906972_Personal.jpg,/upload/messageImage/1523283570897_Personal.jpg&quot;,
goodsDetailPrice: 188,
goodsDetailSpec: &quot;&quot;,
goodsId: &quot;00Y1kR4r1029X822731o0&quot;,
isHost: 0,
managerEarn: 0,
postage: 10,
profit: 0,
specA: &quot;白色&quot;,
specB: &quot;64G&quot;,
specC: &quot;小&quot;,
specD: &quot;5寸&quot;,
specE: &quot;套餐二&quot;,
unionEarn: 0,
vipPrice: 0
}, {
c_id: 3135,
costPrice: 0,
discountPrice: 0,
earn: 0,
etime: null,
flag: 0,
goodsDetailCount: 199,
goodsDetailId: &quot;100PgQ2xy08121409mY27&quot;,
goodsDetailInventory: 199,
goodsDetailOff: 0,
goodsDetailPic: &quot;/upload/messageImage/1523281057461_Personal.jpg,/upload/messageImage/1523282906972_Personal.jpg,/upload/messageImage/1523283570897_Personal.jpg&quot;,
goodsDetailPrice: 188,
goodsDetailSpec: &quot;&quot;,
goodsId: &quot;00Y1kR4r1029X822731o0&quot;,
isHost: 0,
managerEarn: 0,
postage: 10,
profit: 0,
specA: &quot;黑色&quot;,
specB: &quot;128G&quot;,
specC: &quot;小&quot;,
specD: &quot;4.7寸&quot;,
specE: &quot;套餐一&quot;,
unionEarn: 0,
vipPrice: 0
}, {
c_id: 3136,
costPrice: 0,
discountPrice: 0,
earn: 0,
etime: null,
flag: 0,
goodsDetailCount: 199,
goodsDetailId: &quot;100PgQ2xy08121409mY27&quot;,
goodsDetailInventory: 199,
goodsDetailOff: 0,
goodsDetailPic: &quot;/upload/messageImage/1523281057461_Personal.jpg,/upload/messageImage/1523282906972_Personal.jpg,/upload/messageImage/1523283570897_Personal.jpg&quot;,
goodsDetailPrice: 188,
goodsDetailSpec: &quot;&quot;,
goodsId: &quot;00Y1kR4r1029X822731o0&quot;,
isHost: 0,
managerEarn: 0,
postage: 10,
profit: 0,
specA: &quot;蓝色&quot;,
specB: &quot;64GG&quot;,
specC: &quot;大&quot;,
specD: &quot;4.5寸&quot;,
specE: &quot;套餐二&quot;,
unionEarn: 0,
vipPrice: 0
}];

// var keys = {
// &apos;颜色&apos;: [&apos;红色&apos;, &apos;白色&apos;],
// &apos;容量&apos;: [&apos;8g&apos;, &apos;16g&apos;, &apos;32g&apos;, &apos;64g&apos;],
// &apos;尺寸&apos;: [&apos;大&apos;, &apos;小&apos;, &apos;大&apos;],
// &apos;套餐&apos;: [&apos;套餐一&apos;, &apos;套餐二&apos;, &apos;套餐三&apos;]
// };
// //SKU，Stock Keeping Uint(库存量单位)
// var sku_list = [{
// &apos;attrs&apos;: &apos;红色|16g|big|套餐二&apos;,
// &apos;price&apos;: 120
// }, {
// &apos;attrs&apos;: &apos;红色|8g|big|套餐一&apos;,
// &apos;price&apos;: 10
// }, {
// &apos;attrs&apos;: &apos;白色|16g|big|套餐二&apos;,
// &apos;price&apos;: 28
// }, {
// &apos;attrs&apos;: &apos;红色|64g|small|套餐三&apos;,
// &apos;price&apos;: 220
// }, {
// &apos;attrs&apos;: &apos;白色|32g|middle|套餐二&apos;,
// &apos;price&apos;: 130
// }, {
// &apos;attrs&apos;: &apos;红色|32g|big|套餐一&apos;,
// &apos;price&apos;: 120
// }, ];
</code></pre><p>实现：主要利用 Object.keys 方法获取对象的 key,value 值，配上 forEach 循环实现最终想要的结果。</p>
<pre><code>var keys = {};
var sku_list = [];
//原数据转换小写
goodsSpecJSON = goodsSpecJSON.map(function (keyo) {
var key = Object.keys(keyo)[0];
var newkey = key.substring(0, 1).toLowerCase() + key.substring(1);
var dic = {};
dic[newkey] = keyo[key];
return dic
});
//生成keys
goodsSpecJSON.forEach(function (keyo) {
var key = Object.keys(keyo)[0]; //[&apos;specA&apos;]
var val = keyo[key]; //颜色
if (!keys.hasOwnProperty(val)) {
keys[val] = [];
}
var hash = {};
goodsSpecList.forEach(function (item, i) {
if (hash[item[key]] === undefined) {
hash[item[key]] = true;
keys[val].push(item[key]);
}
// if (keys[val].indexOf(item[key]) === -1) {
// keys[val].push(item[key]);
// }
});
});
console.log(keys)
//生成sku_list
goodsSpecList.forEach(function (item) {
var dic = {
attrs: &apos;&apos;
};
goodsSpecJSON.forEach(function (keyo, j) {
var key = Object.keys(keyo)[0];
dic.attrs += item[key] + (j === goodsSpecJSON.length - 1 ? &apos;&apos; : &apos;|&apos;);
dic.price = item.goodsDetailPrice;
dic.goodsDetailCount = item.goodsDetailCount;
dic.goodsDetailId = item.goodsDetailId;
});
sku_list.push(dic);
});
console.log(sku_list)
</code></pre><p>输出结果：</p>
<p><img src="https://i.imgur.com/gOOuYv0.png" alt="示例结果"></p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Object-keys/" rel="tag"># Object.keys</a>
          
            <a href="/tags/遍历/" rel="tag"># 遍历</a>
          
        </div>
      

      
      
        <div class="post-widgets">
        

        

        
          
          <div id="needsharebutton-postbottom">
            <span class="btn">
              <i class="fa fa-share-alt" aria-hidden="true"></i>
            </span>
          </div>
        
        </div>
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/08/19/Markdown编辑器/" rel="next" title="简洁的 Markdown 编辑器 Smark">
                <i class="fa fa-chevron-left"></i> 简洁的 Markdown 编辑器 Smark
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/08/28/MarkDown语法总结/" rel="prev" title="MarkDown语法总结">
                MarkDown语法总结 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
        
<script>
  with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='//bdimg.share.baidu.com/static/api/js/share.js?cdnversion='+~(-new Date()/36e5)];
</script>

      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC8zODk1Ni8xNTQ4NA=="></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/1383101481859.jpg"
                alt="你就像谜一样" />
            
              <p class="site-author-name" itemprop="name">你就像谜一样</p>
              <p class="site-description motion-element" itemprop="description">Stay foolish, Stay hungry</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">9</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">9</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">15</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/yourname" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i></a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:yourname@gmail.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i></a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://plus.google.com/yourname" target="_blank" title="Google">
                      
                        <i class="fa fa-fw fa-google"></i></a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://twitter.com/yourname" target="_blank" title="Twitter">
                      
                        <i class="fa fa-fw fa-twitter"></i></a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://www.facebook.com/yourname" target="_blank" title="FB Page">
                      
                        <i class="fa fa-fw fa-facebook"></i></a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://stackoverflow.com/yourname" target="_blank" title="StackOverflow">
                      
                        <i class="fa fa-fw fa-stack-overflow"></i></a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://youtube.com/yourname" target="_blank" title="YouTube">
                      
                        <i class="fa fa-fw fa-youtube"></i></a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-block">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                links
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://segmentfault.com/" title="segmentfault" target="_blank">segmentfault</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-4"><a class="nav-link" href="#数据属性（实际存储属性值的属性）的四大特性："><span class="nav-number">1.</span> <span class="nav-text">数据属性（实际存储属性值的属性）的四大特性：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#访问器属性（不实际存储数据，专门提供对其它数据-变量的保护）的四大特性："><span class="nav-number">2.</span> <span class="nav-text">访问器属性（不实际存储数据，专门提供对其它数据/变量的保护）的四大特性：</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-for-in"><span class="nav-number"></span> <span class="nav-text">1. for..in</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-Object-keys"><span class="nav-number"></span> <span class="nav-text">2. Object.keys</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-Object-getOwnProperty"><span class="nav-number"></span> <span class="nav-text">3. Object.getOwnProperty</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-for-of"><span class="nav-number"></span> <span class="nav-text">4. for..of</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#小结"><span class="nav-number"></span> <span class="nav-text">小结</span></a></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">你就像谜一样</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Pisces</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  
  
  <link rel="stylesheet" href="/lib/needsharebutton/needsharebutton.css">

  
  
  <script src="/lib/needsharebutton/needsharebutton.js"></script>

  <script>
    
      pbOptions = {};
      
          pbOptions.iconStyle = "box";
      
          pbOptions.boxForm = "horizontal";
      
          pbOptions.position = "bottomCenter";
      
          pbOptions.networks = "Weibo,Wechat,Douban,QQZone,Twitter,Facebook";
      
      new needShareButton('#needsharebutton-postbottom', pbOptions);
    
    
  </script>

  

  

  

  

</body>
</html>
